package com.sendpo.zjx.sendpo.activity;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.domain.MerchandiseStoreDomain;
import com.sendpo.zjx.sendpo.net.HttpCode;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.services.AmapLocationService;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;

import org.xutils.common.Callback;
import org.xutils.common.util.DensityUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/8/18.
 */

public class SendpoPindanListActivity extends AppCompatActivity implements AMapLocationListener {

    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;

    @BindView(R.id.backbt)
    RelativeLayout backbt;
    @BindView(R.id.index_head)
    RelativeLayout indexHead;
    @BindView(R.id.area)
    TextView area;
    @BindView(R.id.swiperefresh)
    SwipeRefreshLayout swiperefresh;
    private LinearLayoutManager lm;

    private int currentlastitem=0;
    private boolean lastloading=false;
    private int pagenow=1;
    private AmapLocationService amapLocationService;
    private RecylcerAdaper adpter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sendpopindanlist);
        ButterKnife.bind(this);
        Tools.initStatus(this, R.color.black);
        initComponent();
    }

    private void initComponent() {
        lm = new LinearLayoutManager(this, OrientationHelper.VERTICAL, false);
        recyclerview.setLayoutManager(lm);
        swiperefresh.setColorSchemeColors(getResources().getColor(R.color.default_theme));
        swiperefresh.setProgressViewOffset(false, 0, DensityUtil.dip2px(150));
        swiperefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                amapLocationService = new AmapLocationService(SendpoPindanListActivity.this);
                amapLocationService.setmLocationOption(getDefaultAmapLocationOptions());
                amapLocationService.registerListener(SendpoPindanListActivity.this);
                amapLocationService.start();
            }
        });
        amapLocationService = new AmapLocationService(this);
        amapLocationService.setmLocationOption(getDefaultAmapLocationOptions());
        amapLocationService.registerListener(this);
        amapLocationService.start();
    }
    public AMapLocationClientOption getDefaultAmapLocationOptions() {
        AMapLocationClientOption mLocationOption = null;
        if (mLocationOption == null) {
            mLocationOption = new AMapLocationClientOption();
            //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
            mLocationOption.setLocationCacheEnable(true);
            mLocationOption.setOnceLocation(true);
            mLocationOption.setOnceLocationLatest(false);
            //设置是否返回地址信息（默认返回地址信息）
            mLocationOption.setNeedAddress(true);
            //设置是否强制刷新WIFI，默认为true，强制刷新。
            mLocationOption.setWifiScan(true);
            mLocationOption.setInterval(1000);
            //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
            mLocationOption.setHttpTimeOut(20000);
        }
        return mLocationOption;
    }
    @OnClick(value = {R.id.backbt})
    public void onMyClick(View view) {
        switch (view.getId()) {
            case R.id.backbt:
                finish();
                break;
        }
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
           if(aMapLocation==null){
               swiperefresh.setRefreshing(false);
           return;
           }
         area.setText(""+aMapLocation.getDistrict());
           pagenow=1;
        query(pagenow,aMapLocation.getDistrict());

    }




    public void query(int pagenow, final String userArea) {
        swiperefresh.setRefreshing(true);
        final Map<String, String> map = new HashMap<>();
        map.put("pagenow", pagenow + "");
        map.put("merchantsArea", userArea + "");
        Xutils.POST(HttpUrl.merchandisebylocationbyPindan, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                swiperefresh.setRefreshing(false);
                Gson gson = new Gson();
                MerchandiseStoreDomain domain = gson.fromJson(result, MerchandiseStoreDomain.class);
                switch (domain.getState()) {
                    case HttpCode.SUCCESS:
                        if (domain.getData() != null && domain.getData().size() != 0) {
                            if (adpter == null) {
                                recyclerview.setAdapter(adpter = new RecylcerAdaper(domain.getData(),SendpoPindanListActivity.this));
                                recyclerview.setOnScrollListener(new RecyclerView.OnScrollListener() {
                                    @Override
                                    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                                        super.onScrollStateChanged(recyclerView, newState);
                                        if (currentlastitem == lm.getItemCount() - 1 && newState == RecyclerView.SCROLL_STATE_IDLE) {
                                            if (SendpoPindanListActivity.this.pagenow == 1 && adpter.dataBeen.size() >= 10 && lastloading == false) {
                                                SendpoPindanListActivity.this.pagenow++;
                                                append(SendpoPindanListActivity.this.pagenow,userArea);
                                            }
                                        }
                                    }

                                    @Override
                                    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                                        super.onScrolled(recyclerView, dx, dy);
                                        currentlastitem = lm.findLastVisibleItemPosition();
                                    }
                                });
                            } else {
                                adpter.initRefresh(domain.getData());
                            }

                        }

                        break;
                    case HttpCode.ERROR:
                  //      Toast.makeText(getApplicationContext(),""+domain.getMessage(),Toast.LENGTH_SHORT).show();
                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                swiperefresh.setRefreshing(false);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    public void append(int pagenow, final String userArea) {
        lastloading=true;
        Map<String, String> map = new HashMap<>();
        map.put("pagenow", pagenow + "");
        map.put("merchantsArea", userArea + "");
        Xutils.POST(HttpUrl.merchandisebylocationbyPindan, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                lastloading = false;
                Gson gson = new Gson();
                MerchandiseStoreDomain domain = gson.fromJson(result, MerchandiseStoreDomain.class);
                switch (domain.getState()) {
                    case HttpCode.SUCCESS:
                        if (domain.getData() != null && domain.getData().size() != 0) {
                            if (adpter == null) {
                                recyclerview.setAdapter(adpter = new RecylcerAdaper(domain.getData(),SendpoPindanListActivity.this));
                                recyclerview.setOnScrollListener(new RecyclerView.OnScrollListener() {
                                    @Override
                                    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                                        super.onScrollStateChanged(recyclerView, newState);
                                        if (currentlastitem == lm.getItemCount() - 1 && newState == RecyclerView.SCROLL_STATE_IDLE) {
                                            if (SendpoPindanListActivity.this.pagenow == 1 && adpter.dataBeen.size() >= 10 && lastloading == false) {
                                                SendpoPindanListActivity.this.pagenow++;
                                                append(SendpoPindanListActivity.this.pagenow,userArea);
                                            }
                                        }
                                    }

                                    @Override
                                    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                                        super.onScrolled(recyclerView, dx, dy);
                                        currentlastitem = lm.findLastVisibleItemPosition();
                                    }
                                });
                            } else {
                                adpter.initAppend(domain.getData());
                            }

                        }
                        break;
                    case HttpCode.ERROR:
                        Toast.makeText(getApplicationContext(),""+domain.getMessage(),Toast.LENGTH_SHORT).show();
                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                lastloading = false;
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    public class RecylcerAdaper extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        public List<MerchandiseStoreDomain.DataBean> dataBeen;
        public LayoutInflater inflater;

        public RecylcerAdaper(List<MerchandiseStoreDomain.DataBean> dataBeen, Context context) {
            inflater = LayoutInflater.from(context);
            this.dataBeen = dataBeen;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            RecyclerView.ViewHolder ih = null;
            ih = new IndexHoler(inflater.inflate(R.layout.layout_sendpopindan_listitem, parent, false));
            return ih;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
            IndexHoler ih = (IndexHoler) holder;
                  final MerchandiseStoreDomain.DataBean dataBean=dataBeen.get(position);

              if(dataBean.getMerchandiseimgs()!=null&&dataBean.getMerchandiseimgs().size()!=0){
                  Glide.with(SendpoPindanListActivity.this)
                          .load(""+dataBean.getMerchandiseimgs().get(0))
                          .asBitmap()
                          .placeholder(getResources().getColor(R.color.default_lightgray))
                          .override(500, 500)
                          .centerCrop()
                          .into(ih.head_img);
              }
              ih.name.setText(""+dataBean.getMerchandiseName());
             ih.count_tv.setText(dataBean.getMerchandisePindannum()+"人单");
            ih.nowprice_tv.setText(""+dataBean.getMerchandiseCurrentprice());
            ih.originprice_tv.setText(""+dataBean.getMerchandiseOriginalprice());
            ih.rootView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("merchandiseId", dataBean.getMerchandiseId());
                    Tools.redirectActivity(SendpoPindanListActivity.this, GeneicStoreInfoActivity.class, map);
                }
            });
          ih.pindan_bt.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View view) {
                  Map<String, Object> map = new HashMap<>();
                  map.put("merchandiseId", dataBean.getMerchandiseId());
                  Tools.redirectActivity(SendpoPindanListActivity.this, GeneicStoreInfoActivity.class, map);
              }
          });
            ih.peoplenum_tv.setText("已有"+dataBean.getBuypeople()+"人参与");
        }

        @Override
        public int getItemCount() {
            return dataBeen.size();
        }

        public class IndexHoler extends RecyclerView.ViewHolder {
            public View rootView;
            public ImageView head_img;
            public TextView count_tv;
            public TextView nowprice_tv;
            public TextView originprice_tv;
            public TextView name;
            public Button pindan_bt;
            public TextView peoplenum_tv;
            public IndexHoler(View itemView) {
                super(itemView);
                rootView = itemView;
                peoplenum_tv=itemView.findViewById(R.id.peoplenum_tv);
                head_img = itemView.findViewById(R.id.head_img);
                count_tv=itemView.findViewById(R.id.count_tv);
                nowprice_tv=itemView.findViewById(R.id.nowprice_tv);
                originprice_tv=itemView.findViewById(R.id.originprice_tv);
                name=itemView.findViewById(R.id.name);
                pindan_bt=itemView.findViewById(R.id.pindan_bt);
            }
        }
        public void initRefresh(List<MerchandiseStoreDomain.DataBean> domains) {
            this.dataBeen.removeAll(this.dataBeen);
            this.dataBeen.addAll(domains);
            notifyDataSetChanged();
        }

        public void initAppend(List<MerchandiseStoreDomain.DataBean> domains) {
            this.dataBeen.addAll(domains);
            notifyDataSetChanged();
        }

        public void delete(int position) {
            this.dataBeen.remove(position);
            notifyDataSetChanged();
        }

        public void deleteRow(int position) {
            dataBeen.remove(position);
            notifyDataSetChanged();
        }
    }

}
